package com.it.gw.modules.station.activity

import LoginVo
import android.annotation.SuppressLint
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.didi.drouter.utils.TextUtils
import com.it.common.utils.DisplayUtil
import com.it.common.utils.RvSpacesItemUtils
import com.it.data.manager.AppCacheManager
import com.it.data.network.rsp.GQStationVo
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityGqstationListBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.modules.main.viewmodel.MainViewModel
import com.it.gw.modules.station.adapter.GQStationListAdapter
import com.it.gw.modules.station.viewmodel.GQStationViewModel
import com.tencent.mmkv.MMKV


//测站列表
class GQStationListActivity : BaseActivity<ActivityGqstationListBinding>() {

    companion object {
        const val PAGE_SIZE = 20
        const val TAG = "GQStationListActivity"
    }

    private var pageNum = 1
    private val gqStationLis by lazy { mutableListOf<GQStationVo>() }
    private val gqStationListAdapter by lazy {
        GQStationListAdapter(context = this, datas = gqStationLis, listener = {
            val intent = Intent(this, GQStationInfoActivity::class.java)
            intent.putExtra("STCD", it.STCD)
            startActivity(intent)
        })
    }

    override fun initObserver() {

        gqStationViewModel.pageGQStationVoListLiveData.observe(this) {
            ProgressDialog.hide()
            loadMoreData = false
            binding.swipeRefreshLayout.isRefreshing = false
            if (it.result) {
                if (it.data?.list.isNullOrEmpty()) {
                    if (pageNum > 1) {
                        pageNum--
                        Toast.makeText(this, "没有更多数据了！", Toast.LENGTH_SHORT).show()
                    } else {
                        //第一次就没数据
                        gqStationLis.clear()
                        gqStationListAdapter.notifyDataSetChanged()
//                    llNoData.setVisibility(View.VISIBLE);
//                    srHasData.setVisibility(View.GONE);
                    }

                } else {
//                llNoData.setVisibility(View.GONE);
//                srHasData.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        gqStationLis.clear()
                    }
                    gqStationLis.addAll(it.data!!.list!!)
                    Log.d(TAG, "initObserver: pageGQStationVoListLiveData ${gqStationLis}")
                    gqStationListAdapter.notifyDataSetChanged()

                }
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_LONG).show()
            }


        }

    }


    @SuppressLint("RestrictedApi")
    override fun initListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            clearSeachView()
            pageNum = 1
            getGQStationList()
        }
        binding.rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取布局管理器
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager

                // 获取最后一个可见的 item 的位置
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 获取总的 item 数量
                val totalItemCount = layoutManager.itemCount

                // 判断是否滑动到了底部
                if (totalItemCount >= PAGE_SIZE && lastVisibleItemPosition == totalItemCount - 1) {
                    // 滑动到了底部，执行相关操作
                    loadMoreData()
                }
            }
        })
        binding.llSearch.rlSearch.setOnClickListener {
            ProgressDialog.show(this)
            pageNum = 1
            getGQStationList()
        }
        //请选择行政区划
        binding.llSearch.addvcd.setOnClickListener {
            showAddvcdWheelPickDialog(okAction = {
                val text2 =
                    if (select2Position >= 0) list2?.get(select2Position)?.text else ""
                val text3 =
                    if (select3Position >= 0) list3?.get(select3Position)?.text else ""



                if (!TextUtils.isEmpty(text2) && !TextUtils.isEmpty(text3)) {
                    binding.llSearch.addvcd.text = "${text2}/${text3}"
                    addvcd = list3?.get(select3Position)?.id
                } else if (!TextUtils.isEmpty(text2)) {
                    binding.llSearch.addvcd.text = "${text2}"
                    addvcd = list2?.get(select2Position)?.id
                } else if (!TextUtils.isEmpty(text3)) {
                    binding.llSearch.addvcd.text = "${text3}"
                    addvcd = list3?.get(select3Position)?.id
                } else {
                    binding.llSearch.addvcd.text = null
                    addvcd = null
                }
            })
        }
        //请选择测站类型
        binding.llSearch.sttp.setOnClickListener {
            showSttpWheelViewDialog(okAction = { index ->
                binding.llSearch.sttp.text = sttpList?.get(index)?.key
                sttp = sttpList?.get(index)?.value
            })
        }
        //请选择运维状态
        binding.llSearch.quedeal.setOnClickListener {
            showQuedealWheelViewDialog(okAction = { index ->
                binding.llSearch.quedeal.text = queDealList?.get(index)?.second
                quedeal = queDealList?.get(index)?.first
            })
        }
        //请选择数据来源
        binding.llSearch.projecttype.setOnClickListener {
            //选择数据来源
            showProjecttypeWheelViewDialog(okAction = { index ->
                binding.llSearch.projecttype.text = projecttypeList?.get(index)?.second
                projecttype = projecttypeList?.get(index)?.first
            })

        }
    }

    private var loadMoreData = false;
    private fun loadMoreData() {
        if(loadMoreData){
            return
        }
        Log.d(TAG, "loadMoreData: ")
        pageNum += 1
        loadMoreData = true;
        getGQStationList()
    }

    override fun initData() {
        ProgressDialog.show(this)
        getGQStationList()

    }


    private fun getGQStationList() {
        val userId = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.id
        userId?.let { uId ->
            gqStationViewModel.getGQStationList(
                userId = uId,
                pageNum,
                PAGE_SIZE,
                addvcd = addvcd,
                sttp = sttp,
                projecttype = projecttype,
                quedeal = quedeal,
                stnm = binding.llSearch.stnm.text.toString(),
            )
        }
    }

    override fun initView() {
        setTitle(
            title = R.string.str_gq_station_lis,
            isBack = true,
            tvRightRes1 = R.string.str_select,
            tvRight1Action = {
                if (binding.llSearch.root.visibility == View.VISIBLE) {
                    binding.llSearch.root.visibility = View.GONE
                    clearSeachView()

                } else {
                    binding.llSearch.root.visibility = View.VISIBLE
                    clearSeachView()
                }

            }
        )

        val map = hashMapOf(RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(this, 10f))
        binding.rvList.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvList.adapter = gqStationListAdapter


    }

    private fun clearSeachView() {
        addvcd = null
        sttp = null
        projecttype = null
        quedeal = null
        stnm = null
        binding.llSearch.addvcd.text = null
        binding.llSearch.sttp.text = null
        binding.llSearch.projecttype.text = null
        binding.llSearch.quedeal.text = null
        binding.llSearch.stnm.text = null

    }

    override fun setContentView() {
        binding = ActivityGqstationListBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}